import router from '@/router/router'
import store from '@/store';
import {view} from "../router/view";

let isLoadRouter = false
router.beforeEach((to, from, next) => {
  const {path,fullPath,query,params,meta} = to;
  //是否已经登录
  let isLogin = store.state.user.isLogin
  if (isLogin){
    //  注册路由
  if (!isLoadRouter) {
    generateRouter();
    next({ path: fullPath, replace: true });
    return
  }


    //没有权限
    if (!to.meta.hasAuth ) {
      next('/notAllow');
      return
    }
    if(!['/','/login'].includes(fullPath)){
      store.commit('ADD_TAB', {path,fullPath,query,params,meta});
      next();
    }
    fullPath === '/' &&  next();
    //已经登录了，不能再打开登录页
    fullPath === "/login" ? next("/") : next();
  }else {
    fullPath === '/login' ?  next() : next("/login");
  }
})

export const hasSeeAuthority = (id ) =>{
  let permission = store.state.user.permission,
    auth = permission && permission.find(item => item.function_id === id);
  return auth && auth.is_see
};
export const getAuthority = (id) =>{
  let permission = store.state.user.permission,
    auth = permission && permission.find(item => item.function_id === id);
  return auth;
}


// 动态路由
export const generateRouter = () =>{
  let menu = eachRoutes(view);
  store.commit('SET_MENU',menu)
  isLoadRouter = true;
}

const eachRoutes = (data) => {
  let menu  = [];
  data.forEach(item => {
    //判断可见权限
    let hasAuth = item.meta.auth_id  ? hasSeeAuthority(item.meta.auth_id) : true

    let obj = {
      path: item.path,
      name: item.name,
      component: item.component,
      meta: {...item.meta,hasAuth },
    }

    //有权限的或没有用在菜单显示的 注册路由
    if (item.path && item.component && (hasAuth || !item.meta.isMenu)){
      router.addRoute('home',obj)
    }

    obj.children = eachRoutes(item.children || [])
    if (hasAuth || obj.children.length){
      menu.push(obj)
    }
  });
  return menu
}
